package com.hua.api.modules.express.rest;

import cn.hutool.core.io.IoUtil;
import com.alibaba.fastjson.JSONObject;
import com.hua.api.core.framework.annotation.AnonymousAccess;
import com.hua.api.core.framework.http.response.OpenApiResponse;
import com.hua.api.core.framework.util.Result;
import com.hua.api.core.framework.util.exception.ApiError;
import com.hua.api.core.out.express.imdada.request.BalanceQueryRequest;
import com.hua.api.core.out.express.imdada.request.CancelReasonsRequest;
import com.hua.api.core.out.express.imdada.request.CityCodeListRequest;
import com.hua.api.modules.express.service.impl.ImDadaExpressInfoServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;

@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/imdada")
public class ImdadaController {


    public final ImDadaExpressInfoServiceImpl imDadaExpressInfoService;


    @AnonymousAccess
    @ResponseBody
    @PostMapping(value = "callback")
    public JSONObject callback(HttpServletRequest request){
        log.info("达达回调消息 callback");
        JSONObject result = new JSONObject();
        try {
            String body = IoUtil.read(request.getInputStream(),Charset.forName("utf-8"));
            log.info("body={}",body);
            JSONObject data = JSONObject.parseObject(body);
            imDadaExpressInfoService.onOrderStatusChange(data);
        } catch (IOException e) {
            e.printStackTrace();
        }

        result.put("status","ok");
        return result;
    }


    // 物流单加价
    @AnonymousAccess
    @RequestMapping("/balance/query")
    public Result balance( ) {
        BalanceQueryRequest request = new BalanceQueryRequest();
        OpenApiResponse response = request.doRequest();
        return  Result.of(response.toJSONObject());
    }

    // 物流单加价
    @AnonymousAccess
    @RequestMapping("/citys")
    public Result citys( ) {
        CityCodeListRequest request = new CityCodeListRequest();
        OpenApiResponse response = request.doRequest();
        return  Result.of(response.toJSONObject());
    }

    // 物流单加价
    @AnonymousAccess
    @RequestMapping("/cancel/reson")
    public Result cancelReson() {
        CancelReasonsRequest request = new CancelReasonsRequest();
        OpenApiResponse response = request.doRequest();
        if (!response.isError){
            return Result.of(response.toJSONObject().getJSONArray("result"));
        }else {
            return Result.error(ApiError.Type.LOGIC_ERROR.toException(response.errMsg));
        }
    }

}
